package com.example.forum2.controller;

import com.example.forum2.common.AppResult;
import com.example.forum2.common.ResultCode;
import com.example.forum2.congif.AppConfig;
import com.example.forum2.model.Article;
import com.example.forum2.model.ArticleReply;
import com.example.forum2.model.User;
import com.example.forum2.services.IArticleReplyService;
import com.example.forum2.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags="帖子回复接口")
@Slf4j
@RestController
@RequestMapping("/articleReply")
public class ArticleReplyController {
    @Resource
    private IArticleService iArticleService;
    @Resource
    private IArticleReplyService iArticleReplyService;
//    前端传递的是一个正文和文章id
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子id")@RequestParam("articleId")@NonNull Long articleId,
                            @ApiParam("帖子内容")@RequestParam("content")@NonNull String content){
//        获取用户,判断用户的状态
        HttpSession session=request.getSession(false);
        User user=(User)session.getAttribute(AppConfig.USER_SESSION);
//        判断用户是否被禁言
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
//        获取要回复的帖子,对帖子进行判断
        Article article=iArticleService.selectById(articleId);
        if(article==null||article.getDeleteState()==1||article.getState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
//构造回复对象
        ArticleReply articleReply=new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        iArticleReplyService.createReplyArticle(articleReply);
        return AppResult.success();
    }

//获取回复的列表
    @ApiOperation("获取回复的帖子")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@RequestParam("articleId")Long articleId){
//        首先是根据id检验帖子是否存在
        Article article=iArticleService.selectById(articleId);
        if(article==null||article.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
//        调用service,返回结果
        List<ArticleReply> list=iArticleReplyService.selectByArticleId(articleId);
        return AppResult.success(list);
    }

}
